<?php defined('SYSPATH') or die('No direct script access.');

// URL: /<context>/index.php/Home/
class Controller_Project extends Controller_Base 
{
	const MODULE_NAME = "Project";
	
	private $categoryService;
	private $postService;
	private $progressService;
	private $invitationService;
	
	public function __construct(Request $request, Response $response)
	{
		parent::__construct($request, $response);
		
		$this->categoryService = new Service_GenericSeedniaServiceStub(WSROOT.WSCONTEXT.'/'.SERVICE_CATEGORY.'/', ACCESS_TOKEN);
		$this->categoryService->init($this->_requestContext);

		$this->postService = new Service_PostServiceStub(WSROOT.WSCONTEXT.'/'.SERVICE_POST.'/', ACCESS_TOKEN);
		$this->postService->init($this->_requestContext);
	
		$this->progressService = new Service_GenericSeedniaServiceStub(WSROOT.WSCONTEXT.'/'.SERVICE_PROGRESS.'/', 'ns1.ProgressDto');
		$this->progressService->setAccessToken('seedniaPhpUi');
		$this->progressService->init($this->_sessionInfo);
		
		$this->invitationService = new Service_GenericSeedniaServiceStub(WSROOT.WSCONTEXT.'/'.SERVICE_INVITATION.'/', ACCESS_TOKEN);
		$this->invitationService->init($this->_requestContext);
	}
	
	protected function getXid()
	{
		$xid = parent::getXid();
		if ($xid == NULL)
			$xid = $this->_sessionInfo->currentProjectSid;
		return $xid;
	}
	
	private function loadDefaultContent(&$template)
	{
		$projectXid = $this->getXid();
		$project = NULL;
		if (is_numeric($projectXid)) {
			$project = $this->_projectHelper->loadProject($this->template, $projectXid);
			$this->_projectHelper->loadMembers($this->template, $project->sid);
		}
		$this->_requestContext->project = $project;

		// Member informatio of the user in current session
		$xid = $projectXid.':'.$this->_sessionInfo->userInfo['userSid'];
		$projectMember = $this->_projectHelper->getProjectMemberService()->getByXid($xid);
		$this->template->set_global("projectMember", $projectMember);

		return $project;
	}
	
	public function after()
	{
		$this->loadDefaultContent($this->template);
		
		parent::after();
	}
		
	public function action_index()
	{
		$contentFrame = $this->index('Seednia::Project', '', 'default_sbar_left');
		$content = $this->createView('project_content');
		$contentFrame->content = $content;

		$projectXid = $this->getXid();

		try {
			$cateCriteria = array('kind' => 'Post');
			$ref_categories = $this->categoryService->getList($cateCriteria, 0, 10);
			$content->ref_categories = Util_Data::toMapptingArray($ref_categories, 'sid', 'name');

			//$postCriteria = array('creatorSid' => $this->_sessionInfo->userInfo['userSid'], '_retrieveScope'=> 3);
			$postCriteria = array('_retrieveScope'=> 2);
			$tagsCsv = $this->request->query('tagsCsv');
			if ($tagsCsv === null)
				$tagsCsv = $this->request->post('tagsCsv');
			if ( $tagsCsv != null)
				$postCriteria['postTagNamesCsv'] = $tagsCsv;

			if ($this->_sessionInfo->currentProjectSid != null) {
				$postCriteria['projectSid'] = $projectXid;

				$this->_projectHelper->loadProgress($this->template);
			}

			$content->posts = $this->postService->getPostList($postCriteria, 0, 15);

		} catch (Exception $ex)
		{
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Add action_index: ' . $ex->getMessage());
		}

	}
		
	public function action_activateproject()
	{			
		$activeProjectXid = $this->request->param('xid');
		if ($activeProjectXid != null) {
			$fields = array('userSid' => $this->_sessionInfo->userInfo['userSid']
					, 'activeProjectSid' => $activeProjectXid);
			$this->_profileHelper->getUserService()->updateRaw($fields, 'activeproject');
			$this->setActiveProjectSid($activeProjectXid);
		}
		$redirTo = controller_base_path($this->_requestContext, CONTROLLERPAGE).'/Project';	
		$this->request->redirect($redirTo);
	}
	public function action_form()
	{
		if ($this->request->method() == "GET") {
			$this->showForm();
		} else if ($this->request->method() == "POST") {
			$this->doProcessForm();
		}
	}
	
	private function showForm()
	{
		$title = "Seednia::New Goal";
		$project = null;
		$projectXid = $this->getXid();
		$isNew = ($projectXid == 'new');
		
		if ($isNew) {
			$this->template->set_global("enableProjectNavBar", false);
			$project = new ArrayObject;
			$project->domainId = $this->_requestContext->domainId;
		} else {
			// TODO: this function is called agatin at :after()
			$project = $this->loadDefaultContent($this->template);
			$title = "Seednia::Goal ".$project->name;
		}
		$contentFrame = $this->loadViews($title, '_default_', 'default_sbar_right', 'default_sbar_left');		
		$content = $this->createView('project_form');
		$contentFrame->content = $content;
		
		$content->project = $project;
		
		$cateCriteria = array('kind' => 'Project');
		$ref_categories = $this->categoryService->getList($cateCriteria, 0, 10);
		$content->ref_categories = Util_Data::toMapptingArray($ref_categories, 'sid', 'name');
	}
	
	private function doProcessForm()
	{
		$projectXid = $this->getXid();
		$isNew = ($projectXid == 'new');
		
		try {
			$record = $this->loadFormParams();
			$record['creatorSid'] = $this->_sessionInfo->userInfo['userSid'];
			// save profile image
			$image = array();
			$error = $this->_resourceHelper->saveFileResource($image, $this->_requestContext, 'profileImage', 'media');
			$image['creatorSid'] = $this->_sessionInfo->userInfo['userSid'];
			$record['profileImage'] = $image;
			
			if ($isNew) {
				$sid = $this->_projectHelper->addProject($record);
				if ($sid != null) {
					$this->setActiveProjectSid($sid);
					
					$sid = $this->resourceService->add($resource);
				} else {
					Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Project | Message: addProject returned null');
				}
			} else {
				$this->_projectHelper->updateProject($record);
			}

			$redirTo = controller_base_path($this->_requestContext, CONTROLLERPAGE).'/Project';
			$this->request->redirect($redirTo);
		} catch (Exception $ex)
		{
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Login | Message: ' . $ex->getMessage());
		}
	}
	
	private function loadFormParams()
	{
		require_once Kohana::find_file('classes', 'util');
		$record = array();
		
		$record['domainId'] = $this->request->post('domainId');
		$record['sid'] = $this->request->post('sid');
		$record['id'] = $this->request->post('id');
		$record['categorySid'] = $this->request->post('categorySid');
		$record['name'] = $this->request->post('name');
		$record['goal'] = $this->request->post('goal');
		$record['description'] = $this->request->post('description');
		$record['planStartDate'] = datetime_format_convert($this->request->post('planStartDate'),  $this->_sessionInfo->userInfo['dateFormat'], FORMAT_DATE_ISO);
		$record['planEndDate'] = datetime_format_convert($this->request->post('planEndDate'),  $this->_sessionInfo->userInfo['dateFormat'], FORMAT_DATE_ISO);
		$record['tagNamesCsv'] = $this->request->post('tagNamesCsv');
		$record['requiredSkillTagNamesCsv'] = $this->request->post('requiredSkillTagNamesCsv');

		return $record;
	}
	
	////////// Milestone //////////
	
	public function action_milestones()
	{
		if ($this->request->method() == "GET") {
			$this->showMilestonesForm();
		} else if ($this->request->method() == "POST") {
			$this->doProcessMilestoneForm();
		}
	}
	
	private function showMilestonesForm()
	{
		$contentFrame = $this->loadViews('Seednia::Milestones', '_default_',  'default_sbar_right', 'default_sbar_left' );
		$content = $this->createView('project_milestone_form');
		$contentFrame->content = $content;
		
		try {
			//$this->loadDefaultContent($this->template);

			$content->milestones = $this->_projectHelper->loadProgress($this->template);
			$content->projectSid = $this->_requestContext->projectSid;

			$cateCriteria = array('kind' => 'Progress');
			$ref_categories = $this->categoryService->getList($cateCriteria, 0, 10);
			$content->ref_categories = Util_Data::toMapptingArray($ref_categories, 'sid', 'name');

		} catch (Exception $ex)
		{
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Login | Message: ' . $ex->getMessage());
		}
	}
	
	private function doProcessMilestoneForm()
	{
		try {
			$record = array();
			$record['sid'] = (int)$this->request->post('sid');
			$record['projectSid'] = (int)$this->request->post('projectSid');
			$record['creatorSid'] = (int)$this->_sessionInfo->userInfo['userSid'];
			$record['name'] = $this->request->post('name');
			$record['description'] = $this->request->post('description');
			$record['priority'] = $this->request->post('priority');
			$record['planStartDt'] = datetime_format_convert($this->request->post('planStartDt'),  $this->_sessionInfo->userInfo['dateFormat'], FORMAT_DATE_ISO);
			$record['planEndDt'] = datetime_format_convert($this->request->post('planEndDt'),  $this->_sessionInfo->userInfo['dateFormat'], FORMAT_DATE_ISO);
			
			if ($record['sid'] == NULL) {
				$sid = $this->progressService->add($record);
			} else {
				$sid = $this->progressService->update($record);
			}

			$redirTo = controller_base_path($this->_requestContext, CONTROLLERPAGE).'/Project/editmilestones';
			$this->request->redirect($redirTo);
		} catch (Exception $ex)
		{
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Login | Message: ' . $ex->getMessage());
		}
	}

	////////// Members //////////
	
	public function action_showmembers()
	{
		$contentFrame = $this->index('Seednia::Project Members', '', 'default_sbar_left');
		$content = $this->createView('project_members');
		$contentFrame->content = $content;
		
		//$this->loadDefaultContent($this->template);
				
		$memberRequests = $this->_projectHelper->loadMemberRequests();
		$content->invited = $memberRequests[0];
		$content->memberRequests = $memberRequests[1];
		
		$invitationCriteria = array('projectSid' => $this->_sessionInfo->currentProjectSid);
		$memberRequestCriteria['status'] = 2;
		$content->invitedEmails = $this->invitationService->getList($invitationCriteria, 0, 20);

	}
	
	/**
	 * A member invite a user to join the project
	 */
	public function action_invite()
	{
		$record = array();
		$record['projectSid'] = $this->request->query('projectSid'); // projectSid
		$record['userSid'] = $this->request->query('userSid'); // userSid
		$record['type'] = $this->request->query('type'); // request type
		$record['role'] = $this->request->query('role'); // role

		$result = $this->_projectHelper->addProjectMember($record);

		$redirTo = controller_base_path($this->_requestContext, CONTROLLERPAGE).'/Project/showmembers';	
		$this->request->redirect($redirTo);
	}
	
	/**
	 * a member invite (possibly non-seednia members) by email
	 */
	public function action_inviteemails()
	{
		$emails = explode($this->request->post('emails'));
		
		foreach ($emails as $email) {
			$email = trim($email);
			
			$record = array();
			$record['inviteeEmail'] = $email; // userSid
			$record['projectSid'] = $this->request->post('projectSid'); // projectSid
			$record['projectMemberType'] = 'collab';
			$record['kind'] = 'teammate';	
			
			$result = $this->invitationService->add($record);
		}

		$redirTo = controller_base_path($this->_requestContext, CONTROLLERPAGE).'/Project/showmembers';	
		$this->request->redirect($redirTo);
	}
	
	/**
	 * A user request to joing the project
	 */
	public function action_requestjoin()
	{
		$record = array();
		$record['projectSid'] = $this->request->query('projectSid'); // request uuid
		$record['userSid'] = $this->request->query('userSid'); // userSid
		$record['type'] = $this->request->query('type'); // type
		$record['role'] = $this->request->query('role'); // role

		$result = $this->_projectHelper->getProjectMemberService()->add($record, 'request/join/');

		$redirTo = controller_base_path($this->_requestContext, CONTROLLERPAGE).'/Home';	
		$this->request->redirect($redirTo);
	}
	
	public function action_respondrequest()
	{
		$fields = array();
		$fields['requestUuid'] = $this->request->query('requestUuid'); // request uuid
		$fields['action'] = $this->request->query('action'); // request uuid
		$fields['reason'] = $this->request->query('reason'); // request uuid

		$this->_projectHelper->getProjectMemberService()->updateRaw($fields, 'request/respond/');

		$redirTo = controller_base_path($this->_requestContext, CONTROLLERPAGE).'/Project/showmembers';	
		$this->request->redirect($redirTo);
	}
	
	////////// Resources //////////
	
	public function action_resources()
	{
		$contentFrame = $this->index('Seednia::'.self::MODULE_NAME, '', 'default_sbar_left');
		$content = $this->createView('resource_content');
		$contentFrame->content = $content;

		$projectSid = $this->getXid();
		try {
			$cateCriteria = array('kind' => 'Resource');
			$ref_categories = $this->categoryService->getList($cateCriteria, 0, 10);
			$content->ref_categories = Util_Data::toMapptingArray($ref_categories, 'sid', 'name');

			// Default form values
			$resource = array('domainId' => $this->_requestContext->domainId);
			$resource['projectSid'] = $projectSid;
			$content->resource = $resource;
			
			$criteria = array('projectSid' => $projectSid);
			// TODO: set privacyLevel
			$resourceService = new Service_GenericSeedniaServiceStub(WSROOT.WSCONTEXT.'/'.SERVICE_RESOURCE.'/', ACCESS_TOKEN);
			$resourceService->init($this->_requestContext);
			$content->resources = $resourceService->getList($criteria, 0, 20);

			$content->return_url = controller_base_path($this->_requestContext, CONTROLLERPAGE).'/Project/'.$projectSid.'/resources';

		} catch (Exception $ex)
		{
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Add action_index: ' . $ex->getMessage());
		}

	}

} // End Controller_Home